package com.sanhe.rfmuscle.activity.work;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import com.sanhe.rfmuscle.databinding.ActivityCardBinding;
import com.sanhe.rfmuscle.event.CarShowEvent;
import com.sanhe.rfmuscle.event.Event;
import com.sanhe.rfmuscle.event.Num1Event;
import com.sanhe.rfmuscle.event.Num2Event;
import com.sanhe.rfmuscle.view.PwdEditText;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class CardActivity extends BaseWorkActivity {

    ActivityCardBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCardBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.back.setOnClickListener(v -> sendTouchEvent((byte) 1, (byte) 0x20));
        binding.ok.setOnClickListener(v -> sendTouchEvent((byte) 1, (byte) 0x6c));

        binding.et.setKeyEventClickListener(new PwdEditText.KeyEventClickListener() {
            @Override
            public void sendData(int key) {
                sendTouchEvent((byte) 0, (byte) (0x60 + key));
            }

            @Override
            public void enter() {
                sendTouchEvent((byte) 1, (byte) 0x6c);
            }

            @Override
            public void backspace() {
                sendTouchEvent((byte) 1, (byte) 0x6b);
            }
        });

        binding.rentingOn.setOnClickListener(v -> sendTouchEvent((byte) 1, (byte) 0x1c));
        binding.rentingOff.setOnClickListener(v -> sendTouchEvent((byte) 1, (byte) 0x1b));

        updateNum1();
        updateNum2();
        updateState();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Num1Event event) {
        updateNum1();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Num2Event event) {
        updateNum2();
    }

    private void updateNum1() {
        binding.tv.setText(Event.num1Event.getValue() + "");
    }

    private void updateNum2() {
        binding.et.setText(Event.num2Event.getValue() + "");
    }

    @Override
    public void sendTouchEvent(byte data_H, byte data_L) {
        super.sendTouchEvent(data_H, data_L);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CarShowEvent event) {
        updateState();
    }

    private void updateState() {
        if (Event.rentEvent.getValue() == 1) {
            binding.rentingOff.setVisibility(View.INVISIBLE);
            binding.rentingOn.setVisibility(View.VISIBLE);

        } else {
            binding.rentingOff.setVisibility(View.VISIBLE);
            binding.rentingOn.setVisibility(View.INVISIBLE);
        }
    }
}
